<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>猫咪预约 - 猫咖管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 全局样式 */
        :root {
            --primary-color: #D85D5D;
            --secondary-color: #9B7E46;
            --accent-color: #FFA384;
            --light-color: #F8F3EA;
            --dark-color: #333333;
            --success-color: #4CAF50;
            --error-color: #FF5252;
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f9f9f9;
            color: var(--dark-color);
            line-height: 1.6;
        }

        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        /* 顶部导航栏样式 */
        header {
            background-color: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .header-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background-color: var(--primary-color);
            border-radius: 50%;
            position: relative;
        }

        .logo-icon::after {
            content: '';
            position: absolute;
            top: -4px;
            left: -4px;
            width: 48px;
            height: 48px;
            border-radius: 50%;
            border: 1px solid rgba(216, 93, 93, 0.2);
        }

        .logo h1 {
            font-size: 24px;
            color: var(--primary-color);
        }

        nav ul {
            display: flex;
            list-style: none;
            gap: 25px;
        }

        nav a {
            text-decoration: none;
            color: var(--dark-color);
            font-weight: 500;
            padding: 8px 12px;
            border-radius: 4px;
            transition: var(--transition);
            position: relative;
        }

        nav a:hover,
        nav a.active {
            color: var(--primary-color);
        }

        nav a::after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 0;
            width: 0;
            height: 2px;
            background-color: var(--primary-color);
            transition: var(--transition);
        }

        nav a:hover::after,
        nav a.active::after {
            width: 100%;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-info span {
            font-weight: 500;
        }

        .btn {
            padding: 8px 16px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            background-color: #c74d4d;
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid var(--primary-color);
            color: var(--primary-color);
        }

        .btn-outline:hover {
            background-color: var(--primary-color);
            color: white;
        }

        /* 搜索区域 */
        .search-section {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            margin: 30px 0;
        }

        .search-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }

        .search-box {
            flex: 1;
            position: relative;
        }

        .search-box input {
            width: 100%;
            padding: 12px 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            transition: var(--transition);
        }

        .search-box input:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 3px rgba(216, 93, 93, 0.2);
        }

        .search-box i {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
        }

        .categories {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
        }

        .category-btn {
            padding: 8px 16px;
            background-color: #f0f0f0;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            transition: var(--transition);
        }

        .category-btn:hover,
        .category-btn.active {
            background-color: var(--primary-color);
            color: white;
        }

        /* 猫咪列表样式 */
        .main-content {
            padding: 20px 0 60px;
        }

        .section-title {
            text-align: center;
            margin-bottom: 40px;
            position: relative;
        }

        .section-title h2 {
            font-size: 32px;
            color: var(--primary-color);
            display: inline-block;
            margin-bottom: 15px;
        }

        .section-title::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 80px;
            height: 3px;
            background-color: var(--secondary-color);
        }

        .cats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 30px;
        }

        .cat-card {
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            transition: var(--transition);
            cursor: pointer;
        }

        .cat-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        }

        .cat-image {
            height: 200px;
            width: 100%;
            background-size: cover;
            background-position: center;
            position: relative;
        }

        .cat-price {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background-color: var(--primary-color);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-weight: bold;
            font-size: 18px;
        }

        .cat-info {
            padding: 15px;
        }

        .cat-info h3 {
            font-size: 20px;
            margin-bottom: 5px;
            color: var(--dark-color);
        }

        .cat-info .cat-category {
            color: var(--secondary-color);
            font-weight: 500;
            margin-bottom: 10px;
            display: block;
        }

        .cat-info p {
            color: #666;
            font-size: 14px;
            height: 40px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 2000;
            overflow-y: auto;
            padding: 20px;
        }

        .modal-content {
            background-color: white;
            max-width: 800px;
            margin: 40px auto;
            border-radius: 8px;
            overflow: hidden;
            position: relative;
        }

        .close-modal {
            position: absolute;
            top: 15px;
            right: 15px;
            width: 30px;
            height: 30px;
            background-color: rgba(0, 0, 0, 0.3);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 10;
            font-size: 18px;
            transition: var(--transition);
        }

        .close-modal:hover {
            background-color: var(--primary-color);
        }

        .cat-detail {
            display: flex;
            flex-direction: column;
        }

        @media (min-width: 768px) {
            .cat-detail {
                flex-direction: row;
            }
        }

        .detail-image {
            flex: 1;
            height: 400px;
            background-size: cover;
            background-position: center;
            position: relative;
            cursor: zoom-in;
        }

        .detail-image.zoomed {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 3000;
            cursor: zoom-out;
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center;
        }

        .detail-info {
            flex: 1;
            padding: 30px;
        }

        .detail-info h2 {
            font-size: 28px;
            margin-bottom: 10px;
            color: var(--primary-color);
        }

        .cat-meta {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .meta-item {
            display: flex;
            flex-direction: column;
        }

        .meta-label {
            font-size: 14px;
            color: #999;
        }

        .meta-value {
            font-weight: 500;
            font-size: 18px;
        }

        .detail-description {
            margin: 20px 0;
            line-height: 1.8;
        }

        .booking-form {
            background-color: var(--light-color);
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        /* 页脚样式 */
        footer {
            background-color: var(--dark-color);
            color: white;
            padding: 40px 0 20px;
        }

        .footer-content {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 30px;
            margin-bottom: 30px;
        }

        .footer-column h3 {
            font-size: 20px;
            margin-bottom: 20px;
            position: relative;
            padding-bottom: 10px;
        }

        .footer-column h3::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 50px;
            height: 2px;
            background-color: var(--primary-color);
        }

        .footer-links {
            list-style: none;
        }

        .footer-links li {
            margin-bottom: 10px;
        }

        .footer-links a {
            color: #bbb;
            text-decoration: none;
            transition: var(--transition);
        }

        .footer-links a:hover {
            color: white;
            padding-left: 5px;
        }

        .contact-info {
            color: #bbb;
        }

        .contact-info p {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .copyright {
            text-align: center;
            padding-top: 20px;
            border-top: 1px solid #444;
            color: #bbb;
            font-size: 14px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .header-container {
                flex-direction: column;
                gap: 15px;
            }

            nav ul {
                flex-wrap: wrap;
                justify-content: center;
            }

            .search-container {
                flex-direction: column;
            }

            .cat-detail {
                flex-direction: column;
            }

            .detail-image {
                height: 300px;
            }
        }

        /* 加载动画 */
        .loader {
            text-align: center;
            padding: 40px;
            display: none;
        }

        .loader .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid var(--primary-color);
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 4px;
            color: white;
            font-weight: 500;
            z-index: 3000;
            opacity: 0;
            transform: translateX(100%);
            transition: all 0.3s ease;
        }

        .notification.success {
            background-color: var(--success-color);
            opacity: 1;
            transform: translateX(0);
        }

        .notification.error {
            background-color: var(--error-color);
            opacity: 1;
            transform: translateX(0);
        }
        .detail-image {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .upload-icon {
            font-size: 36px;
            color: #aaa;
            opacity: 0.6;
            transition: all 0.3s ease;
        }

        .detail-image:hover .upload-icon {
            opacity: 1;
        }

        /* 添加图片上传预览样式 */
        /* 添加图片上传预览样式 */
        #image-upload {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        #image-upload:hover {
            border-color: var(--primary-color);
        }

        #image-upload.has-image {
            border: none;
        }

        #image-upload img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        #add-cat-form textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            resize: vertical;
            min-height: 80px;
        }

        /* 表单验证错误提示 */
        .error-text {
            color: var(--error-color);
            font-size: 13px;
            margin-top: 5px;
            display: none;
        }

        .form-group.error .error-text {
            display: block;
        }

        .form-group.error input,
        .form-group.error select,
        .form-group.error textarea {
            border-color: var(--error-color);
        }

        .detail-image {
            flex: 1;
            height: 400px;
            background-size: cover;
            background-position: center;
            position: relative;
            transition: background-size 0.3s ease, background-position 0.3s ease;
        }


    </style>
</head>
<body>
<!-- 顶部导航栏 -->
<header>
    <div class="container header-container">
        <div class="logo">
            <div class="logo-icon"></div>
            <h1>猫咖管理系统</h1>
        </div>

        <nav>
            <ul>
                <li><a href="index.html">首页</a></li>
                <li><a href="cat.html" class="active">猫咪预约</a></li>
                <li><a href="cafe.html">咖啡购买</a></li>
                <li><a href="center.html">个人中心</a></li>
                <li><a href="message.html">留言板</a></li>
<!--                <li><a href="shoppingcart.html">购物车</a></li>-->
                <li><a href="orders.html">订单信息</a></li>
                <li><a href="booking.html">预约信息</a></li>
            </ul>
        </nav>

        <!-- 顶部导航栏的用户信息部分 -->
        <div class="user-info">
            <span id="user-display">未登录</span>
            <button class="btn btn-primary" id="logout-btn">退出</button>
        </div>
    </div>
</header>

<!-- 搜索区域 -->
<section class="search-section">
    <div class="container">
        <div class="search-container">
            <div class="search-box">
                <input type="text" id="search-input" placeholder="搜索猫咪名字...">
                <i class="fas fa-search"></i>
            </div>
            <button class="btn btn-primary" id="search-btn">搜索</button>
            <button class="btn btn-outline" id="reset-btn">重置</button>
            <button class="btn btn-primary" id="add-cat-btn">新增猫咪</button>
        </div>

        <div class="categories">
            <button class="category-btn active" data-category="all">全部</button>
            <button class="category-btn" data-category="英短">英短</button>
            <button class="category-btn" data-category="布偶猫">布偶猫</button>
            <button class="category-btn" data-category="波斯猫">波斯猫</button>
            <button class="category-btn" data-category="折耳猫">折耳猫</button>
            <button class="category-btn" data-category="美短">美短</button>
            <button class="category-btn" data-category="其他">其他</button>
        </div>
    </div>
</section>

<!-- 主要内容区域 -->
<section class="main-content">
    <div class="container">
        <div class="section-title">
            <h2>可爱猫咪们</h2>
            <p>选择您心仪的猫咪进行预约</p>
        </div>

        <div class="loader">
            <div class="spinner"></div>
            <p>正在加载猫咪信息...</p>
        </div>

        <div class="cats-grid" id="cats-grid">
            <!-- 猫咪卡片将通过JS动态生成 -->
        </div>
    </div>
</section>

<!-- 猫咪详情模态框 -->
<div class="modal" id="cat-modal">
    <div class="modal-content">
        <div class="close-modal" id="close-modal">
            <i class="fas fa-times"></i>
        </div>
        <div class="cat-detail">
            <div class="detail-image" id="detail-image"></div>
            <div class="detail-info">
                <h2 id="detail-name">猫咪名字</h2>
                <div class="cat-meta">
                    <div class="meta-item">
                        <span class="meta-label">品种</span>
                        <span class="meta-value" id="detail-category">未知</span>
                    </div>
<!--                    <div class="meta-item">-->
<!--                        <span class="meta-label">年龄</span>-->
<!--                        <span class="meta-value" id="detail-age">未知</span>-->
<!--                    </div>-->
                    <div class="meta-item">
                        <span class="meta-label">价格</span>
                        <span class="meta-value" id="detail-price">未知</span>
                    </div>
                </div>

                <p class="detail-description" id="detail-description">
                    猫咪描述信息将显示在这里...
                </p>

                <div class="booking-form">
                    <h3>预约信息</h3>
                    <div class="form-group">
                        <label for="booking-date">预约日期</label>
                        <input type="date" id="booking-date" min="2025-06-17">
                    </div>
                    <div class="form-group">
                        <label for="booking-time">预约时间</label>
                        <select id="booking-time">
                            <option value="">请选择时间段</option>
                            <option value="10:00-12:00">10:00 - 12:00</option>
                            <option value="12:00-14:00">12:00 - 14:00</option>
                            <option value="14:00-16:00">14:00 - 16:00</option>
                            <option value="16:00-18:00">16:00 - 18:00</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="booking-note">备注信息</label>
                        <input type="text" id="booking-note" placeholder="特殊要求或注意事项...">
                    </div>
                    <button class="btn btn-primary" id="booking-btn">立即预约</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!--添加猫咪-->
<div class="modal" id="add-cat-modal">
    <div class="modal-content" style="max-width: 600px;">
        <div class="close-modal" id="close-add-modal">
            <i class="fas fa-times"></i>
        </div>

        <div class="cat-detail" style="flex-direction: column;">
            <h2 style="text-align: center; padding: 20px;">添加新猫咪</h2>

            <div class="detail-image" id="image-upload"
                 style="height: 200px; cursor: pointer; background-color: #f8f9fa; border: 2px dashed #ccc;">
                <i class="fas fa-plus upload-icon"></i>
                <input type="file" id="cat-image-input" accept="image/*" style="display: none;">
            </div>
            <div id="image-name" style="text-align: center; font-size: 12px; color: #666; margin-top: 5px;"></div>

            <div class="detail-info" style="width: 100%;">
                <form id="add-cat-form">
                    <div class="form-group">
                        <label for="cat-name">猫咪名字 *</label>
                        <input type="text" id="cat-name" required>
                        <div class="error-text">请输入猫咪名字</div>
                    </div>

                    <div class="form-group">
                        <label for="cat-category">品种 *</label>
                        <select id="cat-category" required>
                            <option value="">请选择品种</option>
                            <option value="英短">英短</option>
                            <option value="布偶猫">布偶猫</option>
                            <option value="波斯猫">波斯猫</option>
                            <option value="折耳猫">折耳猫</option>
                            <option value="美短">美短</option>
                            <option value="其他">其他</option>
                        </select>
                        <div class="error-text">请选择猫咪品种</div>
                    </div>

                    <div class="form-group">
                        <label for="cat-price">价格（元/小时）*</label>
                        <input type="number" id="cat-price" min="0" step="0.01" required>
                        <div class="error-text">请输入有效的价格</div>
                    </div>

                    <div class="form-group">
                        <label for="cat-description">描述</label>
                        <textarea id="cat-description" rows="3" placeholder="猫咪的个性、特点..."></textarea>
                    </div>

                    <div style="display: flex; gap: 10px; margin-top: 20px;">
                        <button type="button" class="btn btn-outline" id="cancel-add-btn">取消</button>
                        <button type="submit" class="btn btn-primary">添加猫咪</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 页脚 -->
<footer>
    <div class="container">
        <div class="footer-content">
            <div class="footer-column">
                <h3>关于我们</h3>
                <p>猫咖管理系统致力于为猫咪咖啡馆提供专业的管理解决方案，帮助店主高效管理猫咪、咖啡和顾客信息。</p>
            </div>

            <div class="footer-column">
                <h3>快速链接</h3>
                <ul class="footer-links">
                    <li><a href="index.html">首页</a></li>
                    <li><a href="cat.html">猫咪信息</a></li>
                    <li><a href="cafe.html">咖啡菜单</a></li>
                    <li><a href="">在线预订</a></li>
                    <li><a href="center.html">个人中心</a></li>
                </ul>
            </div>

            <div class="footer-column">
                <h3>联系方式</h3>
                <div class="contact-info">
                    <p><i class="fas fa-map-marker-alt"></i> 地址：广东科技学院</p>
                    <p><i class="fas fa-phone"></i> 电话：666666</p>
                    <p><i class="fas fa-envelope"></i> 邮箱：666666.com</p>
                    <p><i class="fas fa-clock"></i> 营业时间：10:00-18:00</p>
                </div>
            </div>
        </div>

        <div class="copyright">
            <p>© 2025 猫咖管理系统 版权所有 | 设计开发：会非的杨</p>
        </div>
    </div>
</footer>

<!-- 通知消息 -->
<div class="notification" id="notification"></div>

<script>
    // API端点配置
    const API_BASE_URL = 'http://localhost:8080/catcafe';
    const CATS_ENDPOINT = `${API_BASE_URL}/query`;
    const BOOKING_ENDPOINT = `${API_BASE_URL}/bookings`;

    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        const catsGrid = document.getElementById('cats-grid');
        const searchInput = document.getElementById('search-input');
        const searchBtn = document.getElementById('search-btn');
        const resetBtn = document.getElementById('reset-btn');
        const categoryBtns = document.querySelectorAll('.category-btn');
        const loader = document.querySelector('.loader');
        const catModal = document.getElementById('cat-modal');
        const closeModal = document.getElementById('close-modal');
        const detailImage = document.getElementById('detail-image');
        const bookingBtn = document.getElementById('booking-btn');
        const notification = document.getElementById('notification');

        let currentCatId = null;
        let activeCategory = 'all';

        const username = localStorage.getItem('username');
        const role = localStorage.getItem('role');
        // 获取显示用户信息的元素
        const userDisplay = document.getElementById('user-display');

        // 如果有用户信息，显示在导航栏
        if (username) {
            // 根据角色显示不同的文本
            const roleText = role === 'admin' ? '管理员' : '普通用户';
            userDisplay.textContent = `${roleText}：${username}`;

            // 添加角色图标和样式（可选）
            userDisplay.innerHTML = `            <i class="fas fa-user-circle"></i>
            <span class="username-text">${username}</span>
            <span class="role-badge">${roleText}</span>
        `;
        } else {
            userDisplay.textContent = "未登录";
        }

        // 退出按钮功能
        const logoutBtn = document.getElementById('logout-btn');
        logoutBtn.addEventListener('click', function () {
            // 清除存储的用户信息
            localStorage.removeItem('username');
            localStorage.removeItem('role');

            // 提示用户并跳转到登录页
            alert('您已成功退出');
            window.location.href = 'login.html'; // 替换为你的登录页面路径
        });

        // 显示加载动画
        function showLoader() {
            loader.style.display = 'block';
            catsGrid.innerHTML = '';
        }

        // 隐藏加载动画
        function hideLoader() {
            loader.style.display = 'none';
        }

        // 显示通知消息
        function showNotification(message, isSuccess = true) {
            notification.textContent = message;
            notification.className = `notification ${isSuccess ? 'success' : 'error'}`;

            setTimeout(() => {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(100%)';
            }, 3000);
        }


        // 获取所有猫咪信息
        function fetchCats() {
            showLoader();

            fetch(CATS_ENDPOINT)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    // 提取 data 字段的内容
                    renderCats(data.data);  // 修改这里
                    hideLoader();
                })
                .catch(error => {
                    console.error('获取猫咪信息失败:', error);
                    hideLoader();
                    catsGrid.innerHTML = '<p class="error">加载猫咪信息失败，请刷新重试</p>';
                });
        }


        // 根据名字搜索猫咪
        function searchCatsByName(name) {
            showLoader();

            fetch(`http://localhost:8080/catcafe/byName?name=${encodeURIComponent(name)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('搜索失败');
                    }
                    return response.json();
                })
                .then(data => {
                    // 提取 data 字段的内容
                    renderCats([data.data]);  // 修改这里
                    hideLoader();
                })
                .catch(error => {
                    console.error('搜索失败:', error);
                    hideLoader();
                    catsGrid.innerHTML = '<p class="error">搜索失败，请重试</p>';
                });
        }


        // 根据分类搜索猫咪
        function searchCatsByCategory(category) {
            if (category === 'all') {
                fetchCats();
                return;
            }

            showLoader();

            fetch(`${CATS_ENDPOINT}?category=${encodeURIComponent(category)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('分类搜索失败');
                    }
                    return response.json();
                })
                .then(data => {
                    // 提取 data 字段的内容
                    renderCats(data.data);  // 修改这里
                    hideLoader();
                })
                .catch(error => {
                    console.error('分类搜索失败:', error);
                    hideLoader();
                    catsGrid.innerHTML = '<p class="error">分类搜索失败，请重试</p>';
                });
        }


        // 获取单个猫咪详情
        function fetchCatDetails(catId) {
            fetch(`${CATS_ENDPOINT}/${catId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取猫咪详情失败');
                    }
                    return response.json();
                })
                .then(cat => {
                    displayCatDetails(cat);
                })
                .catch(error => {
                    console.error('获取猫咪详情失败:', error);
                    showNotification('获取猫咪详情失败', false);
                });
        }

        // 提交预约
        function submitBooking(bookingData) {
            fetch(BOOKING_ENDPOINT, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(bookingData)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('预约失败');
                    }
                    return response.json();
                })
                .then(data => {
                    showNotification('预约成功！', true);
                    closeCatDetail();
                })
                .catch(error => {
                    console.error('预约失败:', error);
                    showNotification('预约失败，请重试', false);
                });
        }

        // 渲染猫咪列表
        function renderCats(cats) {
            catsGrid.innerHTML = '';

            if (!cats || cats.length === 0) {
                catsGrid.innerHTML = '<p class="no-results">没有找到匹配的猫咪，请尝试其他搜索条件。</p>';
                return;
            }

            cats.forEach(cat => {
                console.log("图片路径",cat.image)
                const catCard = document.createElement('div');
                catCard.className = 'cat-card';
                catCard.innerHTML = `
            <div class="cat-image" style="background-image: url('${cat.image || 'https://via.placeholder.com/300'}')">
                <span class="cat-price">¥${cat.price}/小时</span>
            </div>
            <div class="cat-info">
                <h3>${cat.name}</h3>
                <span class="cat-category">${cat.category}</span>
                <p>${cat.description || '暂无描述'}</p>
            </div>
        `;
                catCard.addEventListener('click', () => openCatDetail(cat.id));
                catsGrid.appendChild(catCard);
            });
        }


        // 显示猫咪详情
        function displayCatDetails(cat) {
            // 解析 cat.data 中的实际数据
            const catData = cat.data;

            console.log("解析后的猫咪数据：", catData);

            currentCatId = catData.id;
            localStorage.setItem("catName",catData.name);
            document.getElementById('detail-name').textContent = catData.name;
            document.getElementById('detail-category').textContent = catData.category;
            // document.getElementById('detail-age').textContent = catData.age || '未知';
            document.getElementById('detail-price').textContent = `¥${catData.price}/小时`;
            document.getElementById('detail-description').textContent = catData.description || '暂无详细描述';
            detailImage.style.backgroundImage = `url('${catData.image || 'https://via.placeholder.com/600'}')`;

            // 重置表单
            document.getElementById('booking-date').value = '';
            document.getElementById('booking-time').value = '';
            document.getElementById('booking-note').value = '';

            catModal.style.display = 'block';
            document.body.style.overflow = 'hidden';
        }


        // 打开猫咪详情
        function openCatDetail(catId) {
            fetchCatDetails(catId);
        }

        // 关闭模态框
        function closeCatDetail() {
            catModal.style.display = 'none';
            document.body.style.overflow = 'auto';
            detailImage.classList.remove('zoomed');
        }

        // 图片放大功能
        detailImage.addEventListener('click', function() {
            this.classList.toggle('zoomed');
        });
        // 鼠标悬停放大功能
        detailImage.addEventListener('mousemove', function(e) {
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;

            const scaleX = (x / rect.width) * 100;
            const scaleY = (y / rect.height) * 100;

            this.style.backgroundSize = '300% 300%';
            this.style.backgroundPosition = `${scaleX}% ${scaleY}%`;
        });

// 恢复原图比例
        detailImage.addEventListener('mouseleave', function() {
            this.style.backgroundSize = 'cover';
            this.style.backgroundPosition = 'center';
        });


        // 预约功能
        bookingBtn.addEventListener('click', function() {
            const date = document.getElementById('booking-date').value;
            const time = document.getElementById('booking-time').value;
            const note = document.getElementById('booking-note').value;
            const name=localStorage.getItem("catName");

            if (!date || !time) {
                showNotification('请选择预约日期和时间', false);
                return;
            }

            const bookingData = {
                catId: currentCatId,
                date: date,
                timeSlot: time,
                note: note || '无备注',
                userId: localStorage.getItem('userId') || 'anonymous',
                catName: name
            };

            submitBooking(bookingData);
        });

        // 事件监听器
        searchBtn.addEventListener('click', function() {
            const searchTerm = searchInput.value.trim();
            if (searchTerm) {
                searchCatsByName(searchTerm);
            } else {
                fetchCats();
            }
        });

        resetBtn.addEventListener('click', function() {
            searchInput.value = '';
            document.querySelectorAll('.category-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector('.category-btn[data-category="all"]').classList.add('active');
            activeCategory = 'all';
            fetchCats();
        });

        searchInput.addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                const searchTerm = searchInput.value.trim();
                if (searchTerm) {
                    searchCatsByName(searchTerm);
                }
            }
        });

        categoryBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.category-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');

                const category = this.dataset.category;
                activeCategory = category;
                searchCatsByCategory(category);
            });
        });

        closeModal.addEventListener('click', closeCatDetail);

        // 点击模态框外部关闭
        window.addEventListener('click', function(e) {
            if (e.target === catModal && !detailImage.classList.contains('zoomed')) {
                closeCatDetail();
            }
        });

        // 初始化页面 - 加载所有猫咪
        fetchCats();
    });

    // 获取新增猫咪相关元素
    const addCatBtn = document.getElementById('add-cat-btn');
    const addCatModal = document.getElementById('add-cat-modal');
    const closeAddModal = document.getElementById('close-add-modal');
    const cancelAddBtn = document.getElementById('cancel-add-btn');
    const imageUpload = document.getElementById('image-upload');
    const catImageInput = document.getElementById('cat-image-input');
    const imageNameDisplay = document.getElementById('image-name');
    const addCatForm = document.getElementById('add-cat-form');

    // 当前上传的图片文件
    let currentImageFile = null;

    // 打开新增猫咪模态框
    addCatBtn.addEventListener('click', () => {
        addCatModal.style.display = 'block';
        document.body.style.overflow = 'hidden';
        // 重置表单
        addCatForm.reset();
        currentImageFile = null;
        imageUpload.innerHTML = '<i class="fas fa-plus upload-icon"></i>';
        imageNameDisplay.textContent = '';
        imageUpload.classList.remove('has-image');
    });

    // 关闭新增模态框
    function closeAddCatModal() {
        addCatModal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }

    closeAddModal.addEventListener('click', closeAddCatModal);
    cancelAddBtn.addEventListener('click', closeAddCatModal);

    // 点击图片上传区域触发文件选择
    imageUpload.addEventListener('click', () => {
        catImageInput.click();
    });

    // 处理图片选择
    catImageInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            // 检查文件类型
            if (!file.type.match('image.*')) {
                showNotification('请选择图片文件', false);
                return;
            }

            // 检查文件大小（限制2MB）
            if (file.size > 2 * 1024 * 1024) {
                showNotification('图片大小不能超过2MB', false);
                return;
            }

            currentImageFile = file;

            // 显示预览
            const reader = new FileReader();
            reader.onload = (event) => {
                imageUpload.innerHTML = `<img src="${event.target.result}" alt="猫咪预览">`;
                imageUpload.classList.add('has-image');
                imageNameDisplay.textContent = file.name;
            };
            reader.readAsDataURL(file);
        }
    });

    // 表单验证函数
    function validateForm() {
        let isValid = true;

        // 重置错误状态
        document.querySelectorAll('.form-group').forEach(group => {
            group.classList.remove('error');
        });

        // 检查必填字段
        const requiredFields = ['cat-name', 'cat-category', 'cat-price'];
        requiredFields.forEach(id => {
            const field = document.getElementById(id);
            if (!field.value.trim()) {
                field.closest('.form-group').classList.add('error');
                isValid = false;
            }
        });

        // 验证价格是否为有效数字
        const priceField = document.getElementById('cat-price');
        if (priceField.value && isNaN(parseFloat(priceField.value))) {
            priceField.closest('.form-group').classList.add('error');
            isValid = false;
        }

        return isValid;
    }

    // 提交新增猫咪表单
    addCatForm.addEventListener('submit', (e) => {
        e.preventDefault();

        if (!validateForm()) {
            showNotification('请填写所有必填字段', false);
            return;
        }

        // 收集表单数据
        const formData = new FormData();
        formData.append('name', document.getElementById('cat-name').value);
        formData.append('category', document.getElementById('cat-category').value);
        formData.append('price', document.getElementById('cat-price').value);
        formData.append('description', document.getElementById('cat-description').value);

        // 如果有图片，添加图片文件
        if (currentImageFile) {
            formData.append('image', currentImageFile);
        }

        // 显示加载状态
        const submitBtn = addCatForm.querySelector('button[type="submit"]');
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 添加中...';
        submitBtn.disabled = true;

        // 发送POST请求到后端API
        fetch(`${API_BASE_URL}/add`, {
            method: 'POST',
            body: formData  // 注意：这里不需要设置Content-Type，浏览器会自动设置multipart/form-data
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('添加猫咪失败');
                }
                return response.json();
            })
            .then(data => {
                // showNotification('猫咪添加成功！', true);
                alert("猫咪添加成功")
                location.reload()
                closeAddCatModal();
                // 刷新猫咪列表
                fetchCats();
            })
            .catch(error => {
                console.error('添加猫咪失败:', error);
                showNotification('添加猫咪失败，请重试', false);
            })
            .finally(() => {
                submitBtn.innerHTML = '添加猫咪';
                submitBtn.disabled = false;
            });
    });
</script>
</body>
</html>